<template>
  <a-form :model="ruleForm" v-bind="layout" @finish="handleFinish">
    <a-form-item label="学校名称" name="school_name">
      <a-input v-model:value="ruleForm.school_name" />
    </a-form-item>
    <a-form-item label="学校代码" name="school_code">
      <a-input v-model:value="ruleForm.school_code" />
    </a-form-item>
    <a-form-item label="学校性质" name="school_nature">
      <a-input v-model:value="ruleForm.school_nature" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'

export default {
  name: 'AddorEditSchoolInfo',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
  },
  data() {
    let validateSchool_name = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入用户名");
      } else {
        return Promise.resolve();
      }
    };
    return {
      ruleForm: {
        school_name: '',
        school_code: '',
        school_nature: '',
      },
      rules: {
        school_name: [
          {
            validator: validateSchool_name,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {

    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      formData.append('school_name', values.school_name)
      formData.append('school_code', values.school_code)
      formData.append('school_nature', values.school_nature)
      if (this.url !== '') {
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/unit_management/schools/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
  },
}
</script>
